import Provider from './oauth-client/provider'
import OAuthImplicitRequest from './oauth-client/request'
import querystring from 'querystring'
import axios from 'axios'
import { YcloudLogOut } from '@/api/login'

class AcloudProvider {
  constructor(config) {
    this.sso_uri_prefix = config.sso_uri_prefix
    this.isConfigRedirectUri = config.redirect_uri != null
    this.request = new OAuthImplicitRequest({
      client_id: 'yyc_ycloud-admin', // required
      redirect_uri: process.env.NODE_ENV === 'development' ? 'http://localhost:8000/index' : 'http://192.168.0.150:8080/index'
      // client_id: config.client_id, // required
      // redirect_uri: config.redirect_uri || window.location.href
    })

    this.provider = new Provider({
      id: 'ycloud', // required
      authorization_url: this.sso_uri_prefix + '/oauth/authorize' // required
    })
    this.storage = this.provider.storage
    this.user_info_uri = this.sso_uri_prefix + '/users/info'
    this.logout_uri = this.sso_uri_prefix + '/logout'
    this.menu_uri = config.menu_uri || '/ycloud-authority/res/useridtree'
  }
  getProvider() {
    return this.provider
  }
  login(callback) {
    // Give it to the provider
    let uri = this.provider.requestToken(this.request)
    // Later we need to check if the response was expected
    // so save the request
    this.provider.remember(this.request)
    if (callback) {
      callback()
    } else {
      // Do the redirect
      window.location.href = uri
    }
  }
  logout(callback) {
    // 退出请求
    let logoutRequest = null
    try {
      logoutRequest = {
        lient_id: 'yyc_ycloud-admin',
        // client_id: this.request.client_id,
        redirect_uri: this.isConfigRedirectUri ? this.request.redirect_uri : window.location.href,
        access_token: this.getAccessToken(),
        logout_type: 'slo'
      }

      // uri = this.logout_uri + '?' + querystring.stringify(logoutRequest)
      // this.getProvider().deleteTokens()
      // this.deleteUserInfo()
      // this.deleteMenu()
    } catch (e) {
      console.error('logoutError:', e)
    }
    if (callback) {
      callback()
    } else {
      YcloudLogOut(logoutRequest).then(() => {
        this.getProvider().deleteTokens()
        this.deleteUserInfo()
        this.deleteMenu()
        window.location.href = this.isConfigRedirectUri ? this.request.redirect_uri : window.location.href
      })
      // Do the redirect
    }
  }
  parseResponse() {
    let hash = window.location.hash
    if (hash.indexOf('access_token') !== -1) {
      let response = this.provider.parse(hash)
      return Promise.resolve(response)
    }
  }
  setTokenObj(res) {
    this.provider.setTokenObj(res)
  }
  hasAccessToken() {
    return this.provider.hasAccessToken()
  }
  getAccessToken() {
    return this.provider.getAccessToken()
  }
  setAccessToken(token) {
    this.provider.setAccessToken(token)
  }
  getTokenObj() {
    return this.provider.getTokenObj()
  }
  refreshToken() {
    this.provider.refreshToken()
  }
  setRefreshToken() {
    this.provider.setRefreshToken()
  }
  getUserInfoUri() {
    return this.user_info_uri
  }
  // 设置用户信息
  setUserInfo(userInfo) {
    this.storage.set('user_info', userInfo)
  }
  getUserInfo() {
    return this.storage.get('user_info')
  }
  deleteUserInfo() {
    this.storage.remove('user_info')
  }

  getMenuUri() {
    return this.menu_uri
  }

  // 设置菜单
  setMenu(menu) {
    this.storage.set('menu', menu)
    let urls = []
    for (let m of menu) {
      if (m.raw.value) {
        // debugger
        urls.push(m.raw.value)
      }
      if (m.children) {
        for (let cm of m.children) {
          if (cm.raw.value) {
            // debugger
            urls.push(cm.raw.value)
          }
        }
      }
    }
    this.storage.set('urls', urls)
  }
  getMenu() {
    return this.storage.get('menu')
  }
  deleteMenu() {
    this.storage.remove('menu')
    this.storage.remove('urls')
  }

  hasAuthority(meta) {
    if (!meta.accessControl) {
      return true
    }
    let urls = this.storage.get('urls')
    let find = urls.find(n => n == meta.path)
    if (find) {
      return true
    }
    return false
  }
}

export default AcloudProvider
